package com.summerbird.mallchat.common.chat.service.impl;

import com.summerbird.mallchat.common.chat.dao.ContactDao;
import com.summerbird.mallchat.common.chat.domain.dto.MsgReadInfoDTO;
import com.summerbird.mallchat.common.chat.domain.entity.Contact;
import com.summerbird.mallchat.common.chat.domain.entity.Message;
import com.summerbird.mallchat.common.chat.service.ContactService;
import com.summerbird.mallchat.common.common.utils.AssertUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ContactServiceImpl implements ContactService {

    @Autowired
    private ContactDao contactDao;

    @Override
    public Contact createContact(Long uid, Long roomId) {
        return null;
    }

    @Override
    public Integer getMsgReadCount(Message message) {
        return null;
    }

    @Override
    public Integer getMsgUnReadCount(Message message) {
        return null;
    }

    @Override
    public Map<Long, MsgReadInfoDTO> getMsgReadInfo(List<Message> messages) {
        Map<Long, List<Message>> messageMap = messages.stream().collect(Collectors.groupingBy(Message::getRoomId));
        AssertUtil.equal(messageMap.size(), 1, "只能查同一个房间下的消息");
        Long roomId = messageMap.keySet().iterator().next();
        // 获取接受该消息的用户总数
        Integer totalCount = contactDao.getTotalCount(roomId);
        return messages.stream().map(message -> {
            MsgReadInfoDTO dto = new MsgReadInfoDTO();
            dto.setMsgId(message.getId());
            Integer readCount = contactDao.getReadCount(message);
            dto.setReadCount(readCount);
            dto.setUnReadCount(totalCount - readCount - 1); // 包括自己的一条信息需要排除
            return dto;
        }).collect(Collectors.toMap(MsgReadInfoDTO::getMsgId, Function.identity()));
    }
}
